﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System.Windows;
using Microsoft.AspNetCore.Mvc;          // 提供AddControllers()
using Microsoft.Extensions.DependencyInjection; // 提供IServiceCollection扩展方法

namespace doNet8WebApiDemo;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private IHost _webHost;

    protected override async void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        _webHost = Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseUrls("http://localhost:5000");

                // 关键配置修正点
                webBuilder.ConfigureServices(services =>
                {
                    services.AddControllers(); // 需要Microsoft.AspNetCore.Mvc包
                });

                webBuilder.Configure(app =>
                {
                    app.UseRouting();
                    app.UseEndpoints(endpoints =>
                    {
                        endpoints.MapControllers();
                    });
                });
            })
            .Build();

        await _webHost.StartAsync();
    }

    protected override async void OnExit(ExitEventArgs e)
    {
        await _webHost.StopAsync(); // 关闭时停止Host
        _webHost.Dispose();
        base.OnExit(e);
    }
}

